// import CryptoJS from 'crypto-js'

/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content) {
  uni.showToast({
    icon: 'none',
    title: content
  })
}

/**
* 显示模态弹窗
* @param content 提示的标题
*/
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '提示',
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        resolve(res)
      }
    })
  })
}

/**
* 参数处理
* @param params 参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + "="
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + "="
            result += subPart + encodeURIComponent(value[key]) + "&"
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&"
      }
    }
  }
  return result
}

export const inputPlaceholderStyle = 'color:#999;font-size:32rpx;text-align:left;font-family: PingFang SC, PingFang SC;'

export class CustomPlaceHoder {
  constructor({ color = '#999', fontSize = '32rpx', textAlign = 'left', fontFamily = 'PingFang SC, PingFang SC' }) {
    this.color = color
    this.fontSize = fontSize
    this.textAlign = textAlign
    this.fontFamily = fontFamily
  }

  get styles() {
    return `color: ${this.color};font-size: ${this.fontSize};text-align: ${this.textAlign};font-family: ${this.fontFamily};`
  }
}

export const getEncryptedPhoneNumber = (tel) => {
  return tel?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') || tel
}

function _formatterNormalize(formatter) {
  // 参数归一化
  if (typeof formatter === 'function') {
    return formatter
  }
  if (typeof formatter !== 'string') {
    throw new Error('formatter must be a string or a function')
  }
  if (formatter === 'date') {
    formatter = 'yyyy-MM-dd'
  } else if (formatter === 'datetime') {
    formatter = 'yyyy-MM-dd HH:mm:ss'
  }
  return (dateInfo) => {
    const { yyyy, MM, dd, HH, mm, ss } = dateInfo
    return formatter.replace(/yyyy/g, yyyy)
      .replace(/MM/g, MM)
      .replace(/dd/g, dd)
      .replace(/HH/g, HH)
      .replace(/mm/g, mm)
      .replace(/ss/g, ss)
  }
}

/**
* 格式化一个日期
* @param {Date} date 日期参数
*/
export function dateFormate(date, formatter, isPad = true) {
  formatter = _formatterNormalize(formatter)
  function _pad(value, length) {
    if (isPad) {
      return (value + '').padStart(length, '0')
    } else {
      return value.toString()
    }
  }
  const dateInfo = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    hour: date.getHours(),
    minute: date.getMinutes(),
    second: date.getSeconds(),
    millisecond: date.getMilliseconds()
  }
  dateInfo.yyyy = _pad(dateInfo.year, 4)
  dateInfo.MM = _pad(dateInfo.month, 2)
  dateInfo.dd = _pad(dateInfo.day, 2)
  dateInfo.HH = _pad(dateInfo.hour, 2)
  dateInfo.mm = _pad(dateInfo.minute, 2)
  dateInfo.ss = _pad(dateInfo.second, 2)
  return formatter(dateInfo)
}

export function encrypt(data, key) {
  const keyHex = CryptoJS.enc.Utf8.parse(key)
  const encrypted = CryptoJS.AES.encrypt(data, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

export function decrypt(encryptedData, key) {
  const keyHex = CryptoJS.enc.Utf8.parse(key)
  const decrypted = CryptoJS.AES.decrypt(encryptedData, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

export const publicKey = 'de5NpT6PLSZIyWPQp3nH1Mq29qymFtrn'

export const delay = (milliseconds = 1000) => {
	return new Promise((resolve, reject) => {
		setTimeout(resolve, milliseconds)
	})
}


// 时间日期转换
export	function convertTime(time){
	// 时间日期转换为xx小时前xx天前
	// let now = new Date().getTime();
	// // console.log('now—————————————————')
	// // console.log(now)
	// var minute = 1000 * 60;
	// var hour = minute * 60;
	// var day = hour * 24;
	// let dateTimeStamp = Date.parse(time)
	// // 计算时间差
	// var result = '';
	// var diffValue = now - dateTimeStamp;
	// if (diffValue < 0) {
	//   // console.log("时间不对劲,服务器创建时间与当前时间不同步");
	//   return result = "刚刚";
	// }
	// var dayC = diffValue / day;
	// var hourC = diffValue / hour;
	// var minC = diffValue / minute;
	// if (parseInt(dayC) > 30) {
	//   // result = "" + this.format(dateTimeStamp,"yyyy-MM-dd");
	//   result = "" + "30天前";
	// }else if(parseInt(dayC) > 1) {
	//   result = "" + parseInt(dayC) + "天前";
	// }else if (parseInt(dayC) == 1) {
	//   result = "昨天";
	// } else if (hourC >= 1) {
	//   result = "" + parseInt(hourC) + "小时前";
	// } else if (minC >= 5) {
	//   result = "" + parseInt(minC) + "分钟前";
	// } else{
	//   result = "刚刚";
	// }
	// return result

	// 现在 距离 订单生成时间半小时后 的时间差
	let now = new Date().getTime();
	// console.log('now—————————————————')
	// console.log(now)
	var result = '';
	var minute = 1000 * 60;
	// console.log(time,'time')
	let dateTimeStamp = Date.parse(time)
	// let dateTimeStamp = new Date(time).getTime();//new Date("2024-06-04 19:04:33") 在部分 iOS 下无法正常使用，iOS 只支持 "yyyy/MM/dd"、"yyyy/MM/dd HH:mm:ss"、"yyyy-MM-dd"、"yyyy-MM-ddTHH:mm:ss"、"yyyy-MM-ddTHH:mm:ss+HH:mm" 的格式
	let halfHourMillis = 30 * 60 * 1000;//30分钟对应的毫秒数
	let futureMillis = dateTimeStamp + halfHourMillis
	// 计算时间差
	var diffValue = futureMillis - now;
	// console.log(dateTimeStamp,'dateTimeStamp')
	// console.log(halfHourMillis,'halfHourMillis')
	// console.log(futureMillis,'futureMillis')
	// console.log(diffValue,'diffValue')
	if (diffValue < 0) {
	  return result = 0;
	}else{
	  return result = parseInt(diffValue / minute)
	}
}

// 不能取消订单的时间计算
export	function noCancelTime(time){
	// 现在 距离 订单生成时间半小时后 的时间差
	let now = new Date().getTime();
	// console.log('now—————————————————')
	// console.log(now)
	var result = '';
	var minute = 1000 * 60;
	// console.log(time,'time')
	let dateTimeStamp = Date.parse(time)
	// let dateTimeStamp = new Date(time).getTime();//new Date("2024-06-04 19:04:33") 在部分 iOS 下无法正常使用，iOS 只支持 "yyyy/MM/dd"、"yyyy/MM/dd HH:mm:ss"、"yyyy-MM-dd"、"yyyy-MM-ddTHH:mm:ss"、"yyyy-MM-ddTHH:mm:ss+HH:mm" 的格式

	// 计算时间差
	var diffValue = dateTimeStamp - now;
	// console.log(dateTimeStamp,'dateTimeStamp')
	// console.log(diffValue,'diffValue')
	if (diffValue < 0) {
	  return result = 0;
	}else{
	  return result = parseInt(diffValue / minute)
	}
}
//分支支付
export const setPlay = (res, callback, type = "wxpay", failBack) => {
  // 微信小程序
  /* #ifdef MP */
  uni.requestPayment({
    ...res,
    provider: type,
    // package: res.packageValue,

    success: (result) => {
      callback && callback();
    },
    fail: function (err) {
      console.log("err", err);
      uni.showToast({
        title: "取消支付",
        icon: "none",
      });
      failBack && failBack();
      console.log("fail:", err);
    },
  });
  /* #endif */
};
/****处理衣物条数的*********/
export function expandItems(items) {
  const result = [];

  for (const item of items) {
    // 如果 count 小于等于 1，则直接添加原项
    if (item.count <= 1) {
      result.push(item);
      continue;
    }

    // 如果 count 大于 1，则生成多个 count 为 1 的副本
    for (let i = 0; i < item.count; i++) {
      result.push({ ...item, count: 1 });
    }
  }

  return result;
}
